/**
 * @fileOverview contextmenu
 * @author huangtonger@aliyun.com
 */

const Util = require('../util/');
const Base = require('../simpleBase');

class Component extends Base {
  getDefaultCfg() {
    return {
      /**
       * 类型
       * @type {string}
       */
      type: 'contextmenu',

      /**
       * dom 容器
       * @type {dom}
       */
      container: null
    };
  }

  init() {
    this._initContainer();
  }

  _initContainer() {
    let container = this.container;
    if (container) {
      if (Util.isString(container)) {
        container = document.getElementById(container);
      }
    } else {
      throw new Error('please set the container for the tontextmenu !');
    }
    const commands = container.getElementsByClassName('command');
    container.style.position = 'absolute';
    container.style['z-index'] = 2;
    container.style.top = '0px';
    container.style.left = '0px';
    this.commands = commands;
    this.containerDom = container;
  }

  bindEvent() {
    const commands = this.commands;
    Util.each(commands, command => {
      Util.addEventListener(command, 'click', () => {
        command.className.indexOf('disable') === -1 && this.hide();
      });
    });
  }

  switch(status) {
    const container = this.containerDom;
    const menus = container.getElementsByClassName('menu');
    Util.each(menus, menu => {
      const dataset = menu.dataset;
      if (dataset.status === status) {
        menu.style.display = 'block';
      } else {
        menu.style.display = 'none';
      }
    });
  }

  getCommandDoms() {
    return this.commands;
  }

  show() {
    const containerDom = this.containerDom;
    const editor = this.editor;
    const page = editor.getCurrentPage();
    page.setSignal('preventWheelPan', true);
    containerDom.style.display = 'block';
  }

  hide() {
    const containerDom = this.containerDom;
    const editor = this.editor;
    const page = editor.getCurrentPage();
    page.setSignal('preventWheelPan', false);
    containerDom.style.display = 'none';
  }

  move(clientX, clientY) {
    const containerDom = this.containerDom;
    const boundingRect = Util.getBoundingClientRect(containerDom);
    const top = parseFloat(Util.getStyle(containerDom, 'top'));
    const left = parseFloat(Util.getStyle(containerDom, 'left'));
    containerDom.style.left = left + (clientX - boundingRect.left) + 'px';
    containerDom.style.top = top + (clientY - boundingRect.top) + 'px';
  }
}

module.exports = Component;
